const Influx = require('influx');

const spark_home = process.env.SPARK_HOME;
const setting = require(`${spark_home}/settings/pre_config.json`);
const history1 = setting.history[0];
const history2 = setting.history.length > 0 && setting.history[1];
const { logger } = require('./logging');

//console.log(setting);

/**
 * InfluxDB
 */
const influx = new Influx.InfluxDB({
  database: history1.db,
  username: 'root',
  password: 'root',
  hosts: [{
    host: history1.url.split(":")[0],
    port: history1.url.split(":")[1]
  }],
});

let influx2 = null;
if (history2) {
  influx2 = new Influx.InfluxDB({
    database: history2.db,
    username: 'root',
    password: 'root',
    hosts: [{
      host: history2.url.split(":")[0],
      port: history2.url.split(":")[1]
    }],
  });
}

/**
 * InfluxDB查询sql
 */
async function _query(sql) {
  return new Promise((resolve, reject) => {
    influx.query(sql).then(res =>
      resolve(res)
    ).catch(err =>
      reject(err)
    )
  })
}

/**
 * InfluxDB写入event表数据
 * @param values 数值队列 { value:值 ,member0:测点NAME ,type:类型 ,member1:一次设备ID ,member2:间隔ID ,member3:厂站ID ,almlevel:告警等级 ,text:描述 ,time:毫秒时间戳 }
 */
async function _writeEvent(values) {
  const table = 'event';

  while (values.length > 50000) {
    const v = values.splice(0, 50000);
    _writeEvent(table, v);
  }

  const mean = values.map(item => { 
    return {
      tags: {
        t: item.type,
        m: item.member1,
        l: item.almlevel,
      },
      fields: {
        v: item.value,
        i: item.member0,
        m1: item.member1,
        m2: item.member2,
        m3: item.member3,
        x: item.text,
      },
      timestamp: item.time * 1000000
      //utc时间
      //timestamp: moment.utc(item.time).valueOf() * 1000000
    }
  });
  try {
    if (influx) {
      await influx.writeMeasurement(table, mean);
    }
    if (influx2) {
      await influx2.writeMeasurement(table, mean);
    }
  } catch (err) {
    logger.error(err.message);
  }
}

/**
 * InfluxDB写入history表数据
 * @param values 数值队列 { id:测点ID ,clazz:类型 ,partition:分区 ,value:值 ,raw:原始值 ,quality:质量 ,happen:发生时间 ,time:时间戳 }
 */
async function _writeHistory(values) {
  const table = 'history';

  while (values.length > 50000) {
    const v = values.splice(0, 50000);
    _writeHistory(v);
  }

  const mean = values.map(item => { 
    return {
      tags: {
        i: item.id,
        c: item.clazz,
        p: item.partition
      },
      fields: {
        d: item.value,
        r: item.raw,
        q: item.quality,
        // h: item.happen
      },
      timestamp: item.time * 1000000
      //utc时间
      //timestamp: moment.utc(item.time).valueOf() * 1000000
    }
  });
  try {
    if (influx) {
      await influx.writeMeasurement(table, mean);
    }
    if (influx2) {
      await influx2.writeMeasurement(table, mean);
    }
  } catch (err) {
    logger.error(err.message);
  }
}

module.exports = { _query, _writeEvent, _writeHistory }
